<template>
  <div class="login">
    <nav-bar>
      <span slot="text">{{ isLogin ? '登录' : '注册' }}</span>
    </nav-bar>
    <form>
      <div>
        <input type="text" placeholder="手机号" v-model="phone" />
      </div>
      <div style="position: relative;">
        <input
          :type="isPwd ? 'text' : 'password'"
          placeholder="密码"
          v-model="password"
        />
        <i :class="isPwd ? 'open' : 'close'" @click="isPwd = !isPwd"></i>
      </div>
      <button @click.prevent="submitForm">
        {{ isLogin ? '登录' : '注册' }}
      </button>
    </form>
    <p class="text right" v-if="isLogin" @click="toggle">没有账号? 立即注册</p>
    <p class="text right" v-else @click="toggle">立即登录</p>
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
import { userLogin, registerUser } from '@/network/getData';
import { Local } from '@/common/storage';

export default {
  data() {
    return {
      isLogin: true, // 登录还是注册
      isPwd: false, // 显示密码还是隐藏
      phone: '', // 手机号
      password: '' // 密码
    };
  },
  methods: {
    ...mapMutations(['SAVE_USER_INFO']),
    // 登录注册切换
    toggle() {
      this.phone = '';
      this.password = '';
      this.isPwd = false;
      this.isLogin = !this.isLogin;
    },
    async submitForm() {
      if (this.isLogin) {
        // 登录
        const res = await userLogin({
          phone: this.phone,
          password: this.password
        });
        if (res.code === 200) {
          console.log(res);
          Local.set('token', res.data.token);
          this.SAVE_USER_INFO(res.data.user);
          this.$router.go(-1);
        } else {
          console.log(res.message);
        }
      } else {
        // 注册
        const res = await registerUser({
          phone: this.phone,
          password: this.password
        });
        if (res.code === 200) {
          console.log(res);
          Local.set('token', res.data.token);
          this.SAVE_USER_INFO(res.data.user);
          this.$router.go(-1);
        } else {
          console.log(res.message);
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100vh;
  background-color: #fff;
}
form {
  padding: 100px 10px 0;
  input {
    width: 100%;
    height: 35px;
    display: inline-block;
    text-indent: 10px;
    margin-bottom: 8px;
    border-bottom: 1px solid #ccc;
  }
  i {
    position: absolute;
    top: 40%;
    right: 5px;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
  }
  .open {
    background: url('~@/assets/images/open.png');
    background-size: 100%;
  }
  .close {
    background: url('~@/assets/images/close.png');
    background-size: 100%;
  }
  button {
    width: 100%;
    line-height: 35px;
    border-radius: 5px;
    margin: 10px 0 15px;
    color: #fff;
    background-color: var(--color-base);
  }
}
.text {
  margin-right: 10px;
  font-size: var(--font-size);
}
</style>
